//
//  SFSafariViewController+URLFix.m
//  INMOTION
//
//  Created by 方人疋 on 2018/4/28.
//  Copyright © 2018年 Inmotion. All rights reserved.
//

#import "SFSafariViewController+URLFix.h"
#import <objc/runtime.h>

@implementation SFSafariViewController (URLFix)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method original = class_getInstanceMethod(self.class, @selector(initWithURL:));
        Method swizzling = class_getInstanceMethod(self.class, @selector(ks_initWithURL:));
        BOOL success = class_addMethod(self.class, @selector(initWithURL:), method_getImplementation(swizzling), method_getTypeEncoding(swizzling));
        if (success) {
            class_replaceMethod(self.class, @selector(ks_initWithURL:), method_getImplementation(original), method_getTypeEncoding(original));
        } else {
            method_exchangeImplementations(original, swizzling);
        }
    });
}

- (instancetype)ks_initWithURL:(NSURL *)URL {
    if (URL == nil) {
        return nil;
    }
    if (![URL.absoluteString hasPrefix:@"http://"] && ![URL.absoluteString hasPrefix:@"https://"]) {
        NSString *s = [@"http://" stringByAppendingString:URL.absoluteString];
        return [self ks_initWithURL:[NSURL URLWithString:s]];
    }
    return [self ks_initWithURL:URL];
}

@end
